<!--
 * @Description: 告警类别管理
-->
<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="searchFormData">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table v-loading="loading" :data="tableData" stripe border height="88%"
        @selection-change="handleSelectionChange" ref="tableData">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="alarmTypeName" label="告警类别名称" />
        <el-table-column prop="describe" label="告警类别描述" />
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.alarmTypeId" slot-scope="scope">
            <!--  -->
            <el-button class="text-btn-cursor" type="text" size="small" v-if="judgePermission(22, 'edit')"
              @click="handleEdit(scope.row)">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <!--  -->
            <el-button class="text-btn-cursor cursor-delete" type="text" v-if="judgePermission(22, 'delete')"
              size="small" @click="handleDelete(scope.row.alarmTypeId)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal='false' :title="dialogTitle + '告警类别信息'" :visible.sync="dialogFormVisible"
        :before-close="cancel" width="40%">
        <el-form ref="formData" :rules="rules" :model="formData" label-width="120px" class="demo-ruleForm">
          <el-form-item label="告警类别名称" prop="alarmTypeName">
            <el-input v-model="formData.alarmTypeName" clearable placeholder="请输入告警类别名称" />
          </el-form-item>
          <el-form-item label="告警类别描述" prop="describe">
            <el-input v-model="formData.describe" clearable  placeholder="请输入告警类别描述"/>
          </el-form-item>
          <el-form-item v-if="nowChanceStau === 'add' || nowChanceStau === 'edit'" label="数据类型选择" prop="nowdataType">
            <el-select class="w100p" filterable clearable v-model="formData.nowdataType" multiple @change="addDataType">
              <el-option v-for="(item, index) in dataTypeList" :key="index"
                :value="{ value: item.dataTypeId, name: item.dataTypeName }" :label="item.dataTypeName" />
            </el-select>
          </el-form-item>
          <el-form-item label="所关联数据类型" class="w100p">
            <div class="contact-view">
              <div v-for="(item, index) in formData.alarmTypeDataTypeMapperList" :key="index" class="contact-view-but">
                {{ item.dataTypeName }}
                <i v-if="nowChanceStau === 'add' || nowChanceStau === 'edit'" @click="delDataType(index)"
                  class="el-icon-close"></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';

import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import nowpagereq from "@/api/monitoring-alarm/alarm-category-management";
import dataTypeApi from "@/api/basic-info-manage/data-type-manage";

export default {
  name: "AlarmCategoryManagement",
  components: { BtnSlot, Pagination, MainSlot, SearchForm },
  mixins: [mymixin],
  data() {
    return {
      rules: {
        alarmTypeName: [
          { required: true, message: "请输入告警类别名称", trigger: "blur" }
        ],
        describe: [
          { required: true, message: "请输入告警类别描述", trigger: "blur" }
        ],
        nowdataType: [
          { required: true, message: "请选择数据类型", trigger: "blur" }
        ]
      },
      // 当前数据类型选择的index
      nowdataType: "",
      // 数据类型列表
      dataTypeList: [],
      // 展示的数据类型列表
      showdatatypeList: [],
      // 搜索内容
      searchList: {
        alarmTypeName: ""
      },
      // 选中的数据项数组 alarmTypeId组成 (此数组最多为一个)
      selectIdList: [],
      dialogTitle: "",
      btnList: ['add', 'delete'],
      formItemList: [
        {
          label: '养殖鱼塘',
          type: 'input',
          param: 'alarmTypeName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
      dialogFormVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    dialogFormVisible: {
      handler(status) {
        if (!status) {
          this.$refs['formData'].resetFields()
          console.log('重置表单验证')
        }
      }
    }
  },
  created() {
    // 获取表格数据
    this.search();
    this.getselectlist();
  },
  mounted() { },
  methods: {
    searchFormData(data) {
      this.currentPage = 1;
      this.searchList.alarmTypeName = data.alarmTypeName;
      this.search();
    },
    // 添加一条数据类别
    addDataType() {
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        let addData = this.formData.nowdataType.map(el => {
          return {
            dataTypeId: el.value,
            dataTypeName: el.name
          }
        })
        // Vue 不允许动态添加根级响应式属性，
        // 'alarmTypeDataTypeMapperList'在初始化实例后声明的所以删除项的视图不发生变化

        // this.formData.alarmTypeDataTypeMapperList = addData;
        this.$set(this.formData, 'alarmTypeDataTypeMapperList', addData)
      }
    },
    // 删除一条数据
    delDataType(index) {
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        this.formData.alarmTypeDataTypeMapperList.splice(index, 1);
        this.formData.nowdataType.splice(index, 1);
        console.log(this.formData.alarmTypeDataTypeMapperList)
      }
    },
    // 获取下拉数据
    getselectlist() {
      // 获取所有数据类型
      dataTypeApi.queryExistence().then(res => {
        this.dataTypeList = res.data;
      });
    },

    getTableDataList() {
      this.loading = true;
      this.showdatatypeList = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          systemFlag: "flag",
          ...this.searchList
        }
      };
      nowpagereq.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.errCode !== undefined) {
          this.$message.error("查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
      });
    },
    handleEdit(row) {
      if (row.alarmTypeId) {
        this.formData = JSON.parse(JSON.stringify({ nowdataType: [], ...row }));
        this.formData.nowdataType = row.alarmTypeDataTypeMapperList.map(el => {
          return {
            value: el.dataTypeId,
            name: el.dataTypeName
          }
        });
        this.addActive = true;
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.nowChanceStau = 'edit';
        this.dialogFormVisible = true;
      }
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      let notvalue = true;
      this.selectIdList = list.map(item => {
        if (item.alarmTypeId) {
          return item.alarmTypeId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.selectIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },

    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage();
      }
    },
    delmessage() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      }).then(() => {
        nowpagereq.dellist(this.selectIdList).then(res => {
        if (res.success) {
          this.$message.success("删除成功");
          this.search();
        } else {
          this.$message.error("删除失败");
        }
      });
        })
        .catch(() => {
          this.$message("取消删除");
        });
      
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      }).then(() => {
          nowpagereq.del(data).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("删除成功");
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    closeDialog(){
      this.formData = {};
      this.dialogFormVisible = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          let addparams = {
            ...this.formData,
          };
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // this.formData.routePointMapperList = this.tagsList;
            nowpagereq.editlist(addparams).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.search();
                this.closeDialog();
              } else {
                this.$message.error(res.message||"修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            nowpagereq.addlist(addparams).then(res => {
              if (res.success) {
                this.$message.success("新增成功！");
                this.search();
                this.closeDialog();
              } else {
                this.$message.error(res.message||"新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.contact-view {
  width: 100%;
  // border: #6ecae3 1px solid;
  display: flex;
  flex-wrap: wrap;

  // justify-content: space-between;
  .contact-view-but {
    background-color: #409eff;
    border: 1px solid #409eff;
    color: #fff;
    padding: 0 15px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    margin: 5px;
    text-align: center;
    border-radius: 4px;
    cursor: pointer;

    .el-icon-close {
      height: 30px;
      line-height: 30px;
      float: right;
      padding-left: 6px;
    }
  }
}
</style>
